﻿using System.Collections.Generic;
using HipChat;
using Wolfpack.Core;
using Wolfpack.Core.Interfaces.Entities;
using Wolfpack.Core.Interfaces.Magnum;
using Wolfpack.Core.Publishers;
using System.Linq;

namespace Wolfpack.Contrib.Publishers.HipChat
{
    public class HipChatPublisher : PublisherBase, INotificationEventPublisher
    {
        private HipChatClient _client;
        private readonly HipChatPublisherConfig _config;

        public HipChatPublisher(HipChatPublisherConfig config)
        {
            _config = config;
            Enabled = config.Enabled;
            FriendlyId = config.FriendlyId;
        }

        public override void Initialise()
        {
            Logger.Info("Initialising HipChat publisher connection...");
            _client = new HipChatClient(_config.Token, _config.Room);

            try
            {
                // this is an "admin" level API call - if you don't have an admin token 
                // the call will fail - it's included so you can get a list of your room ids                
                var rooms = _client.ListRoomsAsNativeObjects();
                rooms.ForEach(rm => Logger.Info("\tHipChat Room: {0} [{1}]", rm.Name, rm.Id));
            }
            catch
            {
                Logger.Info("Unable to get list of rooms; requires an Admin token");
            }
        }

        public void Consume(NotificationEvent notification)
        {
            var message = new HipChatMessage();
            var formatters = new List<IMessageFormatter>();

            formatters.Where(f => f.AppliesToNotification(notification))
                .Aggregate(message, (msg, formatter) => formatter.Format(msg, notification));

            if (message.BackgroundColor.HasValue)
                _client.SendMessage(message.Text, message.From, true, message.BackgroundColor.Value);
            else
                _client.SendMessage(message.Text, message.From, true);
        }
    }
}